package com.socket;

import com.socket.handler.SocketClientHandler;
import com.socket.memory.SocketSession;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Timer;
import java.util.TimerTask;

public class SocketClient {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();

    public SocketClient() {
        bootstrap.group(bossGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new SocketClientHandler());
                    }
                });
    }

    public void connect(String ip, int port) {
        try {
            // 连接服务器
            bootstrap.connect(ip, port).sync();

            System.out.println("connect server ok");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void send(ChannelHandlerContext ctx, ByteBuf byteBuf) {
        ChannelFuture channelFuture = ctx.writeAndFlush(byteBuf);
        channelFuture.addListener((cf) -> {
            if (cf.isSuccess()) {
                System.out.println("send to server ok");
            } else {
                System.err.println("send to server fail");
            }
        });
    }

    public void disconnect(ChannelHandlerContext ctx) {
        ctx.disconnect();
    }

    public static void main(String[] args) {
        SocketClient socketClient = new SocketClient();
        socketClient.connect("192.168.0.160", 6800);

        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                ByteBuf byteBuf = Unpooled.buffer();
                byteBuf.writeByte(0x68);
                socketClient.send(SocketSession.get("/192.168.0.160:6800"), byteBuf);
            }
        }, 5000, 10000);
    }
}
